// V-backend/src/controllers/videoController.js
const db = require('../models');
const { Op } = require('sequelize');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 权限检查工具函数
const checkPermission = (req, resourceAnchorId) => {
  const currentUser = req.user;
  const isSuperAdmin = currentUser.role === 'super_admin';
  const isOwner = currentUser.anchor_id === resourceAnchorId;
  
  return {
    hasPermission: isSuperAdmin || isOwner,
    isSuperAdmin,
    isOwner
  };
};

// 视频上传配置
const uploadDir = path.join(__dirname, '../../uploads/videos');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'video-' + uniqueSuffix + ext);
  }
});

const fileFilter = (req, file, cb) => {
  // 允许视频文件
  if (file.mimetype.startsWith('video/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传视频文件！'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 100 * 1024 * 1024 // 100MB
  }
});

const videoController = {
  // 获取视频列表
  getVideos: async (req, res) => {
    try {
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      const { 
        page = 1, 
        limit = 10, 
        status, 
        search,
        category
      } = req.query;
      
      console.log('🎬 获取视频列表:', { 
        anchorId, 
        role: userRole, 
        page, 
        limit, 
        status,
        search,
        category
      });

      // 构建查询条件
      const where = {};
      
      // 权限限制
      if (userRole !== 'super_admin') {
        where.anchor_id = anchorId;
      }
      
      if (status && status !== '') {
        where.status = parseInt(status);
      }
      
      if (category && category !== '') {
        where.category = category;
      }
      
      if (search && search !== '') {
        where[Op.or] = [
          { video_title: { [Op.like]: `%${search}%` } },
          { video_description: { [Op.like]: `%${search}%` } }
        ];
      }

      const videos = await db.Video.findAndCountAll({
        where,
        include: [{
          model: db.Anchor,
          as: 'anchor',
          attributes: ['anchor_name', 'avatar']
        }],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: (page - 1) * limit
      });

      console.log('✅ 视频列表获取成功:', videos.count);

      res.json({
        success: true,
        data: {
          videos: videos.rows,
          pagination: {
            total: videos.count,
            current: parseInt(page),
            pageSize: parseInt(limit),
            totalPages: Math.ceil(videos.count / limit)
          }
        }
      });

    } catch (error) {
      console.error('❌ 获取视频列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取视频列表失败: ' + error.message
      });
    }
  },

  // 获取视频详情
  getVideoById: async (req, res) => {
    try {
      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('🔍 获取视频详情:', { videoId: id, anchorId, role: userRole });

      // 构建查询条件
      const where = { video_id: id };
      
      // 权限限制
      if (userRole !== 'super_admin') {
        where.anchor_id = anchorId;
      }

      const video = await db.Video.findOne({
        where,
        include: [{
          model: db.Anchor,
          as: 'anchor',
          attributes: ['anchor_name', 'avatar']
        }]
      });

      if (!video) {
        return res.status(404).json({
          success: false,
          message: '视频不存在或无权访问'
        });
      }

      console.log('✅ 视频详情获取成功');

      res.json({
        success: true,
        data: video
      });

    } catch (error) {
      console.error('❌ 获取视频详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取视频详情失败: ' + error.message
      });
    }
  },

  // 创建视频
  createVideo: async (req, res) => {
    try {
      const anchorId = req.user.anchor_id;
      const {
        video_title,
        video_description,
        category,
        status = 1
      } = req.body;

      console.log('🎯 创建视频请求:', {
        anchorId,
        video_title,
        video_description,
        category,
        status
      });

      // 验证必要字段
      if (!video_title) {
        return res.status(400).json({
          success: false,
          message: '视频标题为必填项'
        });
      }

      // 创建视频记录
      const video = await db.Video.create({
        anchor_id: anchorId,
        video_title: video_title,
        video_description: video_description || '',
        category: category || '',
        status: parseInt(status),
        video_click_count: 0,
        created_at: new Date()
      });

      console.log('✅ 视频创建成功:', video.video_id);

      res.json({
        success: true,
        message: '视频创建成功',
        data: video
      });

    } catch (error) {
      console.error('❌ 创建视频失败:', error);
      res.status(500).json({
        success: false,
        message: '创建视频失败: ' + error.message
      });
    }
  },

  // 更新视频信息
  updateVideo: async (req, res) => {
    try {
      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      const {
        video_title,
        video_description,
        category,
        status
      } = req.body;

      console.log('✏️ 更新视频请求:', { 
        id, 
        anchorId,
        video_title,
        body: req.body 
      });

      // 查找视频
      const video = await db.Video.findOne({
        where: { video_id: id }
      });
      
      if (!video) {
        console.log('❌ 视频不存在，ID:', id);
        return res.status(404).json({
          success: false,
          message: '视频不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, video.anchor_id);
      console.log('🔐 权限检查结果:', permission);
      
      if (!permission.hasPermission) {
        console.log('❌ 权限不足:', {
          video_owner: video.anchor_id,
          current_user: anchorId,
          user_role: userRole,
          permission
        });
        return res.status(403).json({
          success: false,
          message: '权限不足，只能修改自己创建的视频'
        });
      }

      console.log('✅ 权限检查通过:', permission);

      // 更新视频信息
      const updateData = {};
      if (video_title !== undefined) updateData.video_title = video_title;
      if (video_description !== undefined) updateData.video_description = video_description;
      if (category !== undefined) updateData.category = category;
      if (status !== undefined) updateData.status = parseInt(status);

      console.log('📝 准备更新的数据:', updateData);

      await video.update(updateData);

      console.log('✅ 视频更新成功:', id);

      res.json({
        success: true,
        message: '视频更新成功',
        data: video
      });

    } catch (error) {
      console.error('❌ 更新视频失败:', error);
      res.status(500).json({
        success: false,
        message: '更新视频失败: ' + error.message
      });
    }
  },

  // 删除视频
  deleteVideo: async (req, res) => {
    try {
      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('🗑️ 删除视频请求:', { id, anchorId, userRole });

      // 查找视频
      const video = await db.Video.findOne({
        where: { video_id: id }
      });
      
      if (!video) {
        return res.status(404).json({
          success: false,
          message: '视频不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, video.anchor_id);
      if (!permission.hasPermission) {
        console.log('❌ 权限不足，无法删除视频');
        return res.status(403).json({
          success: false,
          message: '权限不足，只能删除自己创建的视频'
        });
      }

      // 删除视频文件（如果存在）
      if (video.video_url) {
        const filePath = path.join(__dirname, '../..', video.video_url);
        if (fs.existsSync(filePath)) {
          fs.unlinkSync(filePath);
        }
      }

      // 删除封面图片（如果存在）
      if (video.cover_image) {
        const coverPath = path.join(__dirname, '../..', video.cover_image);
        if (fs.existsSync(coverPath)) {
          fs.unlinkSync(coverPath);
        }
      }

      // 删除视频记录
      await video.destroy();

      console.log('✅ 视频删除成功:', id);

      res.json({
        success: true,
        message: '视频删除成功'
      });

    } catch (error) {
      console.error('删除视频失败:', error);
      res.status(500).json({
        success: false,
        message: '删除视频失败: ' + error.message
      });
    }
  },

  // 上传视频文件
  uploadVideoFile: async (req, res) => {
    try {
      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      
      console.log('📹 上传视频文件请求:', { 
        videoId: id, 
        anchorId,
        file: req.file 
      });

      // 查找视频
      const video = await db.Video.findOne({
        where: { video_id: id }
      });
      
      if (!video) {
        // 删除已上传的文件
        if (req.file && fs.existsSync(req.file.path)) {
          fs.unlinkSync(req.file.path);
        }
        return res.status(404).json({
          success: false,
          message: '视频不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, video.anchor_id);
      if (!permission.hasPermission) {
        // 删除已上传的文件
        if (req.file && fs.existsSync(req.file.path)) {
          fs.unlinkSync(req.file.path);
        }
        return res.status(403).json({
          success: false,
          message: '权限不足，只能为自己创建的视频上传文件'
        });
      }

      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '请选择要上传的视频文件'
        });
      }

      // 更新视频URL
      const videoUrl = `/uploads/videos/${path.basename(req.file.path)}`;
      await video.update({
        video_url: videoUrl
      });

      console.log('✅ 视频文件上传成功:', videoUrl);

      res.json({
        success: true,
        message: '视频文件上传成功',
        data: {
          video_url: videoUrl
        }
      });

    } catch (error) {
      console.error('❌ 上传视频文件失败:', error);
      res.status(500).json({
        success: false,
        message: '上传视频文件失败: ' + error.message
      });
    }
  },

  // 上传视频封面
  uploadVideoCover: async (req, res) => {
    try {
      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      
      console.log('🖼️ 上传视频封面请求:', { 
        videoId: id, 
        anchorId,
        file: req.file 
      });

      // 查找视频
      const video = await db.Video.findOne({
        where: { video_id: id }
      });
      
      if (!video) {
        // 删除已上传的文件
        if (req.file && fs.existsSync(req.file.path)) {
          fs.unlinkSync(req.file.path);
        }
        return res.status(404).json({
          success: false,
          message: '视频不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, video.anchor_id);
      if (!permission.hasPermission) {
        // 删除已上传的文件
        if (req.file && fs.existsSync(req.file.path)) {
          fs.unlinkSync(req.file.path);
        }
        return res.status(403).json({
          success: false,
          message: '权限不足，只能为自己创建的视频上传封面'
        });
      }

      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '请选择要上传的封面图片'
        });
      }

      // 更新封面图片URL
      const coverUrl = `/uploads/videos/covers/${path.basename(req.file.path)}`;
      await video.update({
        cover_image: coverUrl
      });

      console.log('✅ 视频封面上传成功:', coverUrl);

      res.json({
        success: true,
        message: '视频封面上传成功',
        data: {
          cover_image: coverUrl
        }
      });

    } catch (error) {
      console.error('❌ 上传视频封面失败:', error);
      res.status(500).json({
        success: false,
        message: '上传视频封面失败: ' + error.message
      });
    }
  },

  // 更新视频状态
  updateVideoStatus: async (req, res) => {
    try {
      const { id } = req.params;
      const { status } = req.body;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('🔄 更新视频状态请求:', { id, status, anchorId, userRole });

      // 查找视频
      const video = await db.Video.findOne({
        where: { video_id: id }
      });
      
      if (!video) {
        return res.status(404).json({
          success: false,
          message: '视频不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, video.anchor_id);
      if (!permission.hasPermission) {
        console.log('❌ 权限不足，无法更新视频状态');
        return res.status(403).json({
          success: false,
          message: '权限不足，只能更新自己创建的视频状态'
        });
      }
      
      await video.update({ status: parseInt(status) });
      
      res.json({
        success: true,
        message: '视频状态更新成功'
      });
    } catch (error) {
      console.error('更新视频状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新视频状态失败'
      });
    }
  },

  // 获取视频统计数据
  getVideoStats: async (req, res) => {
    try {
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('📊 获取视频统计数据:', { anchorId, role: userRole });

      // 构建查询条件
      const where = {};
      if (userRole !== 'super_admin') {
        where.anchor_id = anchorId;
      }

      // 总视频数
      const totalVideos = await db.Video.count({ where });

      // 视频状态分布
      const statusStats = await db.Video.findAll({
        where,
        attributes: [
          'status',
          [db.Sequelize.fn('COUNT', db.Sequelize.col('video_id')), 'count']
        ],
        group: ['status']
      });

      // 分类分布
      const categoryStats = await db.Video.findAll({
        where: {
          ...where,
          category: {
            [Op.ne]: null,
            [Op.ne]: ''
          }
        },
        attributes: [
          'category',
          [db.Sequelize.fn('COUNT', db.Sequelize.col('video_id')), 'count']
        ],
        group: ['category'],
        order: [[db.Sequelize.fn('COUNT', db.Sequelize.col('video_id')), 'DESC']],
        limit: 10
      });

      // 总播放量
      const totalViews = await db.Video.sum('video_click_count', { where });

      const statsData = {
        totalVideos,
        statusStats,
        categoryStats,
        totalViews: totalViews || 0
      };

      console.log('✅ 视频统计数据获取成功');

      res.json({
        success: true,
        data: statsData
      });

    } catch (error) {
      console.error('❌ 获取视频统计数据失败:', error);
      res.status(500).json({
        success: false,
        message: '获取视频统计数据失败: ' + error.message
      });
    }
  }
};

// 导出上传中间件
videoController.uploadVideo = upload.single('video_file');
videoController.uploadCover = upload.single('cover_image');

module.exports = videoController;